<?php
/**
 * TODO : Manager the error and log thing.
 * TODO : X::app()->error->throw('message');
 * TODO : X::app()->log('message', level);
 */

require dirname(__FILE__).'/XFramework/XFramework.php';

class X extends XFramework {
	/**
	 * @var X
	 */
	private static $application;
	
	public $config;
	
	/**
	 * @var XUser
	 */
	public $user;
	/**
	 * @var XSession
	 */
	public $session;
	
	/**
	 * @return X
	 */
	public static function app(){
		if ( null == X::$application )
			X::$application = new X();
		
		return X::$application;
	}
	
	function __construct(){
		$this->config = parse_ini_file('X.ini', true);
		if ( isset($this->config['app']['config'])){
			$confPath = $this->basePath().'/'.$this->config['app']['config'];
			if ( file_exists($confPath) ){
				$this->config['app']['config'] = parse_ini_file($confPath, true);
			}
			else {
				$this->config['app']['config'] = array();
			}
		}
		
		return $this;
	}
	
	private static $inited = false;
	/**
	 * @return X
	 */
	public function init(){
		if ( X::$inited ){
			return $this;
		}
		
		require dirname(__FILE__).'/XFramework/XAutoloader.php';
		$this->setSystemPathAlias();
		
		X::import('Framework.XSession.XSession');
		$this->session = new XSession();
		$this->session->init();
		
		$databaseType = $this->config['database']['type'];
		$databaseHandler = $this->config['database']['handler'];
		X::import('Framework.XDatabase.Schema.'.$databaseType.'.'.$databaseHandler.'.Database');
		
		X::import('Framework.XUser.XUser');
		$this->user = new XUser();
		
		X::import('Framework.XError.XErrorCode');
		X::import('Framework.XData.XString');
		
		X::$inited = true;
		return $this;
	}
	
	private function setSystemPathAlias(){
		$this->pathAlias($this->basePath(), 'Application');
		$this->pathAlias(dirname(__FILE__), 'Framework');
	}
	
	public function basePath(){
		$path = dirname(__FILE__);
		$lastPath = strrchr($path, '/');
		if ( false == $lastPath )
			$lastPath = strrchr($path, '\\');
		$endPos = strlen($path) - strlen($lastPath);
		$path = substr($path, 0, $endPos);
		
		return $path;
	}
}